const LocalStrategy = require('passport-local').Strategy
const Passport = require('passport').Passport
const config = require('config')
const utils = require('utility')
const adminService = require('../services/admin')
const passport = new Passport()
const _ = require('lodash')

passport.serializeUser(function(user, done) {
  done(null, user.id);
})

passport.deserializeUser(async function(id, done) {
  try {
    let user = await adminService.findById(id)
    done(null, _.omit(user, ['password']))
  } catch (err) {
    done(err)
  }
})

passport.use(new LocalStrategy(
  async function(username, password, done) {
    try {
      let user = await adminService.findByName(username)
      if (!user) {
        return done(null, false, { message: '用户不存在' })
      }

      if (user.password !== utils.md5(password + config.sault.op)) {
        return done(null, false, { message: '密码错误' })
      }

      return done(null, user)
    } catch (err) {
      done(err)
    }
  }
))

const auth = function (req, res, next) {
  if (req.isAuthenticated()) {
    next()
    return
  }
  passport.authenticate('local', { session: true }, function(err, user, info) {
    if (err) { return next(err) }
    if (!user) {
      res.status(401).json(info)
      return
    }
    req.logIn(user, function(err) {
      if (err) { return next(err) }
      next()
    })
  })(req, res, next)
}

passport.auth = auth

module.exports = passport